package com.ruoyi.match.job.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.match.constant.CommonConstants;
import com.ruoyi.match.job.service.HalfCourtMatchService;
import com.ruoyi.match.match.domain.Match;
import com.ruoyi.match.match.mapper.MatchMapper;
import com.ruoyi.match.utils.BrowserUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author sjz
 * @version 1.0.0
 * @desc
 * @date 2023/11/7 20:17
 **/
@Slf4j
@RequiredArgsConstructor
@Service
public class HalfCourtMatchServiceImpl implements HalfCourtMatchService {

    private final MatchMapper mapper;

    @Override
    public void halfCourtMatchHandler(WebDriver browser, LocalDate startDate) throws Exception {
        String startTime = startDate.format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
        log.info("执行日期:{} 开始",startTime);
        String matchUrl = String.format(CommonConstants.MATCH_ODDS_URL, startTime);
        browser.get(matchUrl);

        String title = browser.getTitle();
        if("405".equals(title)){
            Thread.sleep(1000);
            browser.navigate().refresh();
            title = browser.getTitle();
            if("405".equals(title)){
                Thread.sleep(1000);
                browser.navigate().refresh();
                title = browser.getTitle();
                if("405".equals(title)) {
                    log.error("被反扒");
                    throw new Exception("被反扒");
                }
            }
        }

        // 获取比赛信息
        WebElement cont = browser.findElement(By.className("cont"));
        WebElement changeDate = cont.findElement(By.xpath("//*[@id=\"ChangeDate\"]/a/span[1]"));
        String changeDateText = changeDate.getText().split(" ")[0];
        LocalDate matchDate = LocalDate.parse(changeDateText, DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));

        if (matchDate.equals(startDate)){
            List<WebElement> touZhuList = browser.findElements(By.className("touzhu_1"));
            for (int j = 0; j < touZhuList.size(); j++) {
                WebElement webElement = touZhuList.get(j);
                String mid = null;
                mid = webElement.getAttribute("data-mid");
                Match match = mapper.selectOne(Wrappers.<Match>lambdaQuery()
                    .select(Match::getId)
                    .eq(Match::getMatchFlag, mid)
                    .isNull(Match::getMatchDate));
                if(match == null){
                    continue;
                }
                String realCs = webElement.findElement(By.xpath("./div[5]/div/p[1]")).getText();
                if ("延期".equals(realCs)) {
                    continue;
                }
                // 暂停销售
//                boolean spfweik1 = BrowserUtil.isExistElement(webElement, );
//                if () {
//
//                }


                WebElement more = webElement.findElement(By.cssSelector(".more"));
                // 创建actions对象
                // 获取js执行器
                JavascriptExecutor javascriptExecutor = (JavascriptExecutor) browser;
                javascriptExecutor.executeScript("arguments[0].scrollIntoView(true);", more);
//            javascriptExecutor.executeScript("window.scrollTo(0,400);");
                javascriptExecutor.executeScript("arguments[0].click();", more);
                ThreadUtil.safeSleep(500);

                try {
                    webElement.findElement(By.className("spfweik_1"));
                    log.info("发现 停售等信息 进行下一场比赛");
                    continue;
                } catch (Exception e) {
                    log.info("未发现 停售等信息 继续进行");
                }

                String ss = null;
                String sp = null;
                String sf = null;
                String ps = null;
                String pp = null;
                String pf = null;
                String fs = null;
                String fp = null;
                String ff = null;
                String half = null;
                // 主队胜赔率
                try {
                    WebElement moreMid = browser.findElement(By.id("more_" + mid));
                    List<WebElement> zk1 = moreMid.findElements(By.className("zk_1"));
                    WebElement zk = zk1.get(4);
                    ss = zk.findElement(By.xpath("./div[1]/div/div[2]")).getText();
                    String attribute = zk.findElement(By.xpath("./div[1]")).getAttribute("data-sp");
                    if (!"0".equals(attribute)) {
                        half = "ss";
                    }

                    sp = zk.findElement(By.xpath("./div[2]/div/div[2]")).getText();
                    attribute = zk.findElement(By.xpath("./div[2]")).getAttribute("data-sp");
                    if (!"0".equals(attribute)) {
                        half = "sp";
                    }

                    sf = zk.findElement(By.xpath("./div[3]/div/div[2]")).getText();
                    attribute = zk.findElement(By.xpath("./div[3]")).getAttribute("data-sp");
                    if (!"0".equals(attribute)) {
                        half = "sf";
                    }


                    ps = zk.findElement(By.xpath("./div[4]/div/div[2]")).getText();
                    attribute = zk.findElement(By.xpath("./div[4]")).getAttribute("data-sp");
                    if (!"0".equals(attribute)) {
                        half = "ps";
                    }

                    pp = zk.findElement(By.xpath("./div[5]/div/div[2]")).getText();
                    attribute = zk.findElement(By.xpath("./div[5]")).getAttribute("data-sp");
                    if (!"0".equals(attribute)) {
                        half = "pp";
                    }

                    pf = zk.findElement(By.xpath("./div[6]/div/div[2]")).getText();
                    attribute = zk.findElement(By.xpath("./div[6]")).getAttribute("data-sp");
                    if (!"0".equals(attribute)) {
                        half = "pf";
                    }

                    fs = zk.findElement(By.xpath("./div[7]/div/div[2]")).getText();
                    attribute = zk.findElement(By.xpath("./div[7]")).getAttribute("data-sp");
                    if (!"0".equals(attribute)) {
                        half = "fs";
                    }

                    fp = zk.findElement(By.xpath("./div[8]/div/div[2]")).getText();
                    attribute = zk.findElement(By.xpath("./div[8]")).getAttribute("data-sp");
                    if (!"0".equals(attribute)) {
                        half = "fp";
                    }

                    ff = zk.findElement(By.xpath("./div[9]/div/div[2]")).getText();
                    attribute = zk.findElement(By.xpath("./div[9]")).getAttribute("data-sp");
                    if (!"0".equals(attribute)) {
                        half = "ff";
                    }
                    Long id = match.getId();
                    mapper.update(null,Wrappers.<Match>lambdaUpdate()
                        .set(Match::getSs, ss)
                        .set(Match::getSp, sp)
                        .set(Match::getSf, sf)
                        .set(Match::getPs, ps)
                        .set(Match::getPp, pp)
                        .set(Match::getPf, pf)
                        .set(Match::getFs, fs)
                        .set(Match::getFp, fp)
                        .set(Match::getFf, ff)
                        .set(Match::getMatchHalfResult,half)
                        .set(Match::getMatchDate,DateUtil.parse(startTime, DatePattern.NORM_DATE_PATTERN))
                        .eq(Match::getId,id));
                } catch (Exception e) {
                    log.error(e.getMessage());
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
